﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.Xrm.Sdk.Metadata;
using System.Text;

using Microsoft.Xrm.Sdk;

namespace VisualRibbonEditor
{
	public partial class ErrorDialog : UserControl, IDialog
	{
		public ErrorDialog (Exception ex, string message = "")
		{
			InitializeComponent();

			StringBuilder sb = new StringBuilder();
			if (!String.IsNullOrEmpty(message)) sb.AppendLine("Application Message: " + message);
			sb.AppendLine("Exception Type: " + ex.GetType().Name);
			if (ex is FaultException)
			{
				FaultException fe = (FaultException)ex;
				sb.AppendLine("Fault Action: " + fe.Action);
				sb.AppendLine("Fault Code: " + fe.Code.Name);
			}
			if (ex is FaultException<OrganizationServiceFault>)
			{
				FaultException<OrganizationServiceFault> feo = (FaultException<OrganizationServiceFault>)ex;
				sb.AppendLine("Fault Action: " + feo.Action);
				if (feo.Code != null) sb.AppendLine("Fault Code: " + feo.Code.Name);
				sb.AppendLine("Error Code: " + feo.Detail.ErrorCode.ToString());
				sb.AppendLine("Error Message: " + feo.Detail.Message);
				sb.AppendLine("Error Trace: " + feo.Detail.TraceText);
			}

			sb.AppendLine("Message: " + ex.Message);
			sb.AppendLine("Error Details: " + ex.ToString());
			sb.AppendLine();
			sb.AppendLine();

			if (MainWindow.CurrentSolution != null && MainWindow.CurrentSolution.RibbonDiffXml != null)
			{
				sb.AppendLine("Current RibbonDiffXml:");
				sb.AppendLine(MainWindow.CurrentSolution.RibbonDiffXml.ToString());
			}
			this.ErrorInfo.Text = sb.ToString();
		}

		private void OKButton_Click(object sender, RoutedEventArgs e)
		{
			if (DialogClosed != null)
			{
				DialogClosed(null);
			}	
		}
		 
		public event CloseDialogHandler DialogClosed;

		private void ErrorDialog_KeyUp(object sender, KeyEventArgs e)
		{
			switch (e.Key) //
			{
				// ESC
				case Key.Escape:
					if (DialogClosed != null) DialogClosed(null);
					break;
				default:
					break;
			}
		}
	}

}
